#!/bin/bash

#变量设置
app_name=api_smart_home
app_path=/home/www/smart_home/api/
pem=~/aliyun.pem
host1=root@119.23.182.1
host2=root@112.74.182.8
app=$app_path$app_name

function do_send_file(){
    echo "开始拷贝公共配置文件到"$host1
    scp -i $pem  $app_path"../conf/app.conf" $host1:~/app.conf.api.public
    echo "开始拷贝公共配置文件到"$host2
    scp -i $pem  $app_path"../conf/app.conf" $host2:~/app.conf.api.public
    echo "公共配置文件拷贝完成!"

    echo "开始拷贝配置文件到"$host1
    scp -i $pem  $app_path"conf/app.conf" $host1:~/app.conf.api
    echo "开始拷贝配置文件到"$host2
    scp -i $pem  $app_path"conf/app.conf" $host2:~/app.conf.api
    echo "配置文件拷贝完成!"

    echo "开始拷贝应用文件到"$host1
    scp -i $pem  $app_path$app_name $host1:~/$app_name
    echo "开始拷贝应用文件到"$host2
    scp -i $pem  $app_path$app_name $host2:~/$app_name
    echo "应用文件拷贝完成!"

    echo "文件发送完成"
}

function do_sync() {

    do_send_file

    echo "开始同步"$host1
    ssh -i $pem $host1 $app_path"server sync"
    echo "开始同步"$host2
    ssh -i $pem $host2 $app_path"server sync"
    echo "同步完成"
}


function do_update() {
    git pull
    go build -gcflags="-l" -o api_smart_home main.go
    mv api_smart_home /home/www/smart_home/api/api_smart_home
    cp -r ./conf /home/www/smart_home/api
    cp -r ../conf /home/www/smart_home

    do_stop
    do_start
}

function do_stop() {
    supervisorctl stop api_smart_home

    for pid in $(ps -ef | grep /home/www/smart_home/api/api_smart_home | grep -v grep | cut -c 15-20); do
        echo $pid
        kill -9 $pid
    done
}

function do_start() {
    supervisorctl start api_smart_home
    tail -f /usr/local/supervisor/logs/api_smart_home.log
}

function do_status() {
    command=`ps aux|grep $app_name |grep -v "grep"`
    if [  "$command" == "" ]
    then
            echo -e "\033[31m$app_name not started \033[0m"
    else
            echo "$app_name is started"
    fi
}


case "$1" in
start)
        echo -n "Starting server"
        do_start
        echo "."
;;
stop)
        echo -n "Stopping  server"
        do_stop
        echo "ok"
;;
update)
        echo -n "Updateing  server..."
        do_update
        do_start
        echo "ok"
;;
restart)
echo -n "Restarting server"
        do_stop
        do_start
;;
status)
        do_status
;;
sync)
        do_sync
        echo "部署完成"
;;
*)
        echo "Usage: ./server {start|stop|update|restart|status|sync}" >&2
        exit 3
;;
esac

exit 0
